package com.zsinfo.guoss.supplier;

import android.Manifest;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.View;
import android.widget.RadioGroup;

import com.example.netcenter.Event.Response;
import com.example.netcenter.RetrofitBuilder;
import com.example.netcenter.Url.ConstantsCode;
import com.example.netcenter.bean.VersionBean;
import com.example.utilcenter.alertUtil.ToastUtil;
import com.example.utilcenter.updateTip.updateTip;
import com.zsinfo.guoss.supplier.base.BaseActivity;
import com.zsinfo.guoss.supplier.fragment.ChinaFragment;
import com.zsinfo.guoss.supplier.fragment.MineFragment;
import com.zsinfo.guoss.supplier.fragment.OverseasFragment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import butterknife.BindView;

public class MainActivity extends BaseActivity implements View.OnClickListener {


    private final String TAG_FRAGMENT_CHINA = "china";
    private final String TAG_FRAGMENT_OVERSEAS = "overseas";
    private final String TAG_FRAGMENT_MINE = "MINE";
    private Fragment lastFragment = null;
    private int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 100;

    @BindView(R.id.main_radio)
    RadioGroup radioGroup;


    @Override
    protected int getContentLayoutRes() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        setTitle("国产水果");

        radioGroup.setOnCheckedChangeListener(onCheckedChangeListener);

        changeFragment(TAG_FRAGMENT_CHINA);

        CheckPermission();
    }


    void CheckPermission() {
        //需要的权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {

            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
        }
    }


    @Override
    protected void initNetData() {


        GetNetCenter().GetNetCenter(RetrofitBuilder.CreateApi().version_check_android(ConstantsCode.version_check_android),
                new Response() {
                    @Override
                    public void OK(Object data) {

                        VersionBean versionBean = (VersionBean) data;


                        PackageInfo packageInfo = null;
                        try {
                            packageInfo = getApplicationContext()
                                    .getPackageManager()
                                    .getPackageInfo(getPackageName(), 0);

                            if (!(packageInfo.versionCode + "").equals(versionBean.getData().getNumber())) {

                                updateTip tip = new updateTip();

                                tip.getUpdateInfo(MainActivity.this, versionBean.getData().getNumber(), versionBean.getData().getUpgradeContent(), MainActivity.this);


                            }

                        } catch (PackageManager.NameNotFoundException e) {
                            e.printStackTrace();
                        }


                    }

                    @Override
                    public void Fail(Throwable e) {

                    }

                    @Override
                    public void complete() {


                    }
                });


    }

    @Override
    protected void customDestroy() {

    }


    /**
     * 生成fragment
     *
     * @param tag
     * @return
     */
    private Fragment getFragmentByTag(String tag) {
        if (TextUtils.isEmpty(tag)) {
            ChinaFragment chinaFragment = new ChinaFragment();
            return chinaFragment;
        }
        switch (tag) {
            case TAG_FRAGMENT_CHINA:
                ChinaFragment chinaFragment = new ChinaFragment();
                return chinaFragment;
            case TAG_FRAGMENT_OVERSEAS:
                OverseasFragment overseasFragment = new OverseasFragment();
                return overseasFragment;

            case TAG_FRAGMENT_MINE:
                MineFragment mineFragment = new MineFragment();
                return mineFragment;

            default:
                return null;

        }


    }


    private void changeFragment(String tag) {
        Fragment fragment = getSupportFragmentManager()
                .findFragmentByTag(tag);
        if (fragment == null) {
            fragment = getFragmentByTag(tag);
            addFragment(fragment, tag);
        } else {
            showFragment(fragment);
        }
        lastFragment = fragment;
    }

    /**
     * 添加fragment
     *
     * @param fragment
     * @param tag
     */
    private void addFragment(Fragment fragment, String tag) {
        FragmentTransaction trans = getSupportFragmentManager()
                .beginTransaction();
        if (lastFragment != null) {
            trans.hide(lastFragment);
        }
        trans.add(R.id.maincontainer, fragment, tag);
        trans.commitAllowingStateLoss();
    }

    /**
     * 显示fragment
     *
     * @param fragment
     */
    private void showFragment(Fragment fragment) {
        FragmentTransaction trans = getSupportFragmentManager()
                .beginTransaction();
        if (lastFragment != null) {
            trans.hide(lastFragment);
        }
        trans.show(fragment);
        trans.commitAllowingStateLoss();
    }


    private RadioGroup.OnCheckedChangeListener onCheckedChangeListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            setShowTitle(true);
            setWindowStatusBarColor(MainActivity.this, R.color.white);
            switch (checkedId) {
                case R.id.radio_button_order:
                    setTitle("国产水果");
                    changeFragment(TAG_FRAGMENT_CHINA);
                    break;
                case R.id.radio_button_count:
                    setTitle("进口水果");
                    changeFragment(TAG_FRAGMENT_OVERSEAS);
                    break;

                case R.id.radio_button_mine:
                    setShowTitle(false);
                    setWindowStatusBarColor(MainActivity.this, R.color.main_color);
                    changeFragment(TAG_FRAGMENT_MINE);

                    break;
                default:
                    break;
            }
        }
    };


    @Override
    public void onClick(View v) {

        downloadAPK(this, "http://app.guoss.cn/download/GSS-Android_V1.4.0.20181112_RC.apk", "1", getPackageName());
    }


    /**
     * 下载最新版本
     */
    public void downloadAPK(final Context context, final String apkUrl, final String version, final String packName) {
        final ProgressDialog dialog = new ProgressDialog(context);
        dialog.setTitle("新版本下载中");
        dialog.setMessage("正在下载中，请稍等");
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setProgress(0);
        dialog.setMax(100);
        dialog.show();
        final Handler handle = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0:
                        dialog.setProgress(msg.arg1);
                        break;
                    case 1:
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                            ToastUtil.showSingleToast(context, "下载失败");
                        }
                        Process.killProcess(Process.myPid());
                        break;
                    case 2:
                        ToastUtil.showSingleToast(context, "请检查存储设置");
                        break;
                    case 3:
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }
                        Uri uri = Uri.fromFile(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), (String) msg.obj));
                        installApk(context, uri, (String) msg.obj, packName);
                        break;
                }
//                super.handleMessage(msg);
            }
        };
        //开启子线程下载最新版本的apk
        new Thread(new Runnable() {
            @Override
            public void run() {
                File file = null;
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

                    file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/guoss_supplier" + version + ".apk");
                    if (!file.exists()) {
                        try {
                            file.createNewFile();
                        } catch (IOException e) {
                            handle.sendEmptyMessage(2);
                            return;
                        }
                    }
                }
                InputStream in = null;
                FileOutputStream fos = null;
                try {
                    URL url = new URL(apkUrl);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.connect();
                    long maxLenght = connection.getContentLength();
                    fos = new FileOutputStream(file);
                    in = connection.getInputStream();
                    int len = 0;
                    int size = 0;
                    byte[] buf = new byte[1024];
                    while ((size = in.read(buf)) != -1) {
                        len += size;
                        fos.write(buf, 0, size);
                        fos.flush();
                        Message msg = handle.obtainMessage();
                        msg.what = 0;
                        msg.arg1 = (int) (len * 100 / maxLenght);
                        handle.sendMessageDelayed(msg, 1000);
                    }
                    fos.close();
                    in.close();
                    Message message = handle.obtainMessage();
                    message.what = 3;
                    message.obj = file.getName();
                    handle.sendMessageDelayed(message, 1000);
                } catch (Exception e) {
                    handle.sendEmptyMessage(1);
                }
            }
        }).start();
    }


    /**
     * 打开安装apk
     */
    private void installApk(Context context, Uri apkUri, String obj, String packName) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            install.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
            File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), obj);
            Uri contentUri = FileProvider.getUriForFile(context, getPackageName() + ".Fileprovider", file);
            install.setDataAndType(contentUri, "application/vnd.android.package-archive");
            startActivity(install);
        } else {
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setDataAndType(apkUri, "application/vnd.android.package-archive");
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // 如果不加上这句的话在apk安装完成之后点击单开会崩溃
            startActivity(install);
        }
//
        Process.killProcess(Process.myPid());
        ActivityManager activitymanager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        activitymanager.restartPackage(context.getPackageName());

    }


}
